import OSS from "ali-oss";
import store from "@/store";
import { nanoid } from "nanoid";
import { message } from "ant-design-vue";
import request from "@/common/utils/request";

let client;
const uploadControllers = {}; // 保存每个文件的 AbortController

// 获取oss的相关配置项
export const createOSSInstance = async (oss_config) => {
  if (client) {
    return client;
  }

  const isSecure = window.location.protocol === "https:";
  client = new OSS({
    bucket: oss_config.bucket,
    region: oss_config.region,
    endpoint: oss_config.endpoint,
    accessKeyId: oss_config.AccessKeyId,
    accessKeySecret: oss_config.AccessKeySecret,
    secure: isSecure,
    connectTimeout: oss_config.durationSeconds * 100,
    timeout: oss_config.durationSeconds * 100,
    stsToken: oss_config.stsToken,
    refreshSTSToken: async () => {
      const reSTS = await request.post(
        "/work_ai",
        "/upload/oss/config/ststoken",
        {
          isRefresh: "1",
        }
      );
      return {
        accessKeyId: reSTS.sts.AccessKeyId,
        accessKeySecret: reSTS.sts.AccessKeySecret,
        stsToken: reSTS.sts.stsToken,
      };
    },
    refreshSTSTokenInterval: 3600 * 1000,
  });

  return client;
};

// oss上传
const retryUpload = async (
  oss,
  fileName,
  uploadFile,
  config,
  maxRetries = 3,      //重试机制     失败后重试3次
  currentRetry = 0,
  signal
) => {
  try {
    const result = await oss.multipartUpload(fileName, uploadFile, {
      partSize: config.partSize || 1024 * 1024 * 5,                // 分片
      parallel: config.parallel || 2,                             // 并发量
      progress: (p, _checkpoint) => {                             // 进度条
        if (signal.aborted) { 
          throw new Error("Upload aborted");
        }
        const uploadProgress = (p * 100).toFixed(0);
        const info = {
          filename: uploadFile.name,
          uploadProgress: uploadProgress,
          upload_id: uploadFile.uid,
        };
        store.dispatch("uploadProgress", info);
      },
      signal, // 传递信号
    });

    return result;
  } catch (error) {
    if (currentRetry < maxRetries && !signal.aborted) {
      await new Promise((resolve) => setTimeout(resolve, 1000));
      return retryUpload(
        oss,
        fileName,
        uploadFile,
        config,
        maxRetries,
        currentRetry + 1,
        signal
      );
    } else {
      const obj = {
        state: false,
        name: uploadFile.name,
      };
      return obj;
    }
  }
};


// 暴露的方法
async function uploadFile(uploadFile, config = {}, atherConfige = {}) {
  
  // 图文剪辑, 每一组的id
  const { parent_id = null, sort = null } = atherConfige
  console.log(parent_id,'组的id', sort, '排序值');
  

  // 1. 获取oss相关配置项
  const response = await request.post(
      "/work_ai",
      "/upload/oss/config/ststoken"
  );


  config.oss_config = response?.sts

  // 2. 初始化oss
  const oss = await createOSSInstance(config.oss_config);

  const uuid = nanoid();
  let fileName


    const index = uploadFile.name.lastIndexOf(".");
    const suffix = uploadFile.name.substring(index + 1);
     fileName = config.SetUploadPath + uuid + "." + suffix;

  console.log(fileName,'fileName----上传的素材name');

  // 创建 AbortController
  const controller = new AbortController();
  uploadControllers[uploadFile.uid] = controller;


  try {
    const result = await retryUpload(
      oss,
      fileName,
      uploadFile,
      config,
      3,
      0,
      controller.signal
    );

    // 上传成功
    if (result.res.status == 200) {
      let nameWithoutExtension = "";
      //  拼出预览地址
      const fileUrl = `${config.oss_config.domain}/${fileName}`;
      nameWithoutExtension = uploadFile.name.substring(
        0,
        uploadFile.name.lastIndexOf(".")
      );

      console.log('清除上传进度 1111');
      clearUpdataList({uploadFile})
      return {
        fileUrl,
        name: nameWithoutExtension,
        // 图文剪辑, 组的id
        parent_id,
        sort
      };
    }
  } catch (error) {
  } finally {
    // 无论成功还是失败，删除控制器
    delete uploadControllers[uploadFile.uid];
  }

  console.log('清除上传进度 2222');
  clearUpdataList({ uploadFile })
  return { state: false, name: uploadFile.name };
}

// 取消上传
export async function cancelUpload(uploadFileUid) {
  const controller = uploadControllers[uploadFileUid];

  if (controller) {
    controller.abort();
    message.success("上传已取消");
    delete uploadControllers[uploadFileUid];
  } else {
    message.warning("未找到上传控制器");
  }
}

export async function upload(file, config = {}, atherConfige={}) {
  return uploadFile(file, config, atherConfige);
}

// 清除上传完成的 上传进度
const clearUpdataList = (params = {}) => {
  const {uploadFile, } = params
  const updataList = store.state.user?.updataList
  console.log(updataList, '上传中 loading的内容11 -- oss');
  const index = updataList.findIndex((item) => item.uid == uploadFile.uid);
  if (index !== -1) {
    updataList.splice(index, 1); 
    store.dispatch("SetUpDateList", updataList);
  }
}